//
//  AuditFinalViewController.m
//  DigiOps
//
//  Created by app on 2018/8/22.
//  Copyright © 2018年 俞渊华. All rights reserved.
//

#import "AuditFinalViewController.h"
#import "FeedBackFormView.h"
#import "FeedBackModel.h"

#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"

#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height
#define CONTACT_HINT @"请输入联系方式"
#define KEY_H      252
#define CONTACT_H 60
#define GAP 10 //上升时底部多留的空隙

@interface AuditFinalViewController () <UIScrollViewDelegate, UITextFieldDelegate,UIImagePickerControllerDelegate>
{
    BOOL isKeyBoardShown;
    CGFloat needRise_H;//本次键盘弹出时,view需要上升的高度
    CGFloat needScroll_H;//本次键盘弹出时,如果文本框未展示完全,scrollview需要向上滚动的距离
    
    UIImageView* addPhoto;
}
@property (nonatomic, strong) UIScrollView *scrollerView;

@end

@implementation AuditFinalViewController
-(void)viewWillAppear:(BOOL)animated
{
    self.scrollerView = [[UIScrollView alloc] init];
    self.scrollerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    if (addPhoto) {
        self.scrollerView.frame = CGRectMake(0, 64, self.view.bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    }
    self.scrollerView.backgroundColor = [UIColor whiteColor];
    self.scrollerView.delegate = self;
    //在这里创建item
    [self createItem];
    
    NSInteger formcount = self.item.formsArray.count;
    CGFloat contentHeight = 0;//累计内容高度
    
    for (NSInteger i = 0; i < formcount; i++) {
        
        FeedBackFormView *formView = [[FeedBackFormView alloc] initWithFrame:CGRectMake(0, contentHeight, self.scrollerView.bounds.size.width, 0) andForm:self.item.formsArray[i]];
        if(i==0)
            formView.form.tag=@"整体审查";
        if (i==1){
            formView.form.tag=@"整体审查1";
            formView.workModel=self.model;

        }
        if (i==2)
            formView.form.tag=@"整体审查2";
        [formView disPlayForm];
        
        formView.keyboardBlock = ^void(UITextView *tv){
            NSInteger a=tv.tag;
            [self keyboardRising:tv];
        };
        formView.blockUser = ^(NSString *user) {
            if (self.blockUser) {
                self.blockUser(user);
            }
        };
        [self.scrollerView addSubview:formView];
        contentHeight += formView.bounds.size.height;
    }
    
    UITextField *contactTF = [[UITextField alloc] initWithFrame:CGRectMake(SEL_H/4, contentHeight+SEL_H/4, SCREEN_W-SEL_H/2, CONTACT_H-SEL_H/2)];
    contactTF.borderStyle = UITextBorderStyleRoundedRect;
    contactTF.delegate = self;
    contactTF.placeholder = CONTACT_HINT;
    contactTF.font = [UIFont systemFontOfSize:15];
    //添加图片的拍照按钮
    if (!addPhoto) {
        addPhoto=[[UIImageView alloc] initWithFrame:CGRectMake(SEL_H/4, contentHeight+SEL_H/4, SCREEN_W-SEL_H/2, CONTACT_H+SEL_H)];
        [addPhoto setImage:[UIImage imageNamed:@"add_photo"]];
    }
    addPhoto.userInteractionEnabled=YES;
    UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addPic)];
    [addPhoto addGestureRecognizer:singleTap];
    
    //    [self.scrollerView addSubview:addPhoto];
    
    UIButton *commitBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    commitBtn.frame = CGRectMake(SEL_H/4, contentHeight+CONTACT_H+SEL_H+SEL_H/2, SCREEN_W-SEL_H/2, CONTACT_H-SEL_H/2);
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    commitBtn.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.1];
    commitBtn.clipsToBounds = YES;
    commitBtn.layer.cornerRadius = 5;
    //    [self.scrollerView addSubview:commitBtn];
    
    self.scrollerView.contentSize = CGSizeMake(self.scrollerView.bounds.size.width, contentHeight+CONTACT_H+CONTACT_H);
    [self.view addSubview:self.scrollerView];
    
    UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleBordered target:self action:@selector(clickEvent)];
    [myButton setTintColor:[UIColor whiteColor]];
//    self.navigationItem.rightBarButtonItem = myButton;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
    //监听键盘下降：
    NSNotificationCenter *noticenter = [NSNotificationCenter defaultCenter];
    [noticenter addObserver:self selector:@selector(keyboardDown) name:UIKeyboardWillHideNotification object:nil];
    
}
-(void)clickEvent{
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        //        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               //    detailVC.model = self.aticleArray[indexPath.row];
                                                               [self.rt_navigationController popViewControllerAnimated:YES complete:nil];
                                                           }];
}
- (NSArray *) titles {
    return @[@"提交"];
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}
-(void)createItem
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"quick_auditfinal" ofType:@"json"];
    FeedBackModel* model = [[FeedBackModel alloc] initWithJsonFilePath:path];
    self.item=model.indexItemArray[0];
}
- (void)addPic {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self cameraClick];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self selectPhotos];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
    }];
    
    [alertController addAction:cameraAction];
    //    [alertController addAction:albumAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 拍摄、相册完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
    [addPhoto setImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)cameraClick {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您没有摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)selectPhotos {
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;//是否可以编辑
    //打开相册选择照片
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}
-(void)keyboardRising:(UIScrollView *)tv
{
    //正在输入文本框的在window的绝对坐标rect
    CGRect rect = [tv convertRect:tv.bounds toView:[[UIApplication sharedApplication] keyWindow]];
    //h:需要上升的高度
    CGFloat h = rect.origin.y + rect.size.height+GAP + KEY_H - SCREEN_H;
    
    if (h <= 0) {//不需要上升
        return;
    }
    
    //当前scrollerView的偏移
    CGPoint offset = self.scrollerView.contentOffset;
    //h2:需要向上滚的高度
    CGFloat h2 = rect.origin.y + rect.size.height+GAP - SCREEN_H;
    
    if (h2 > 0) {//先滚动scrollerView确保文本框被完全显示
        needScroll_H = h2;
        offset.y += needScroll_H;
        self.scrollerView.contentOffset = offset;
    }
    
    needRise_H = h;
    CGRect frame = self.view.frame;
    frame.origin.y -= needRise_H - needScroll_H;
    
    NSLog(@"键盘上升了");
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = frame;
        isKeyBoardShown = YES;
    }];
}



- (void)keyboardDown
{
    if (!isKeyBoardShown) {
        return;
    }
    
    CGRect frame = self.view.frame;
    frame.origin.y += needRise_H - needScroll_H;
    
    NSLog(@"键盘下降了");
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = frame;
        isKeyBoardShown = NO;
        needRise_H = 0;
        needScroll_H = 0;
    }];
}


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self keyboardRising:(UIScrollView *)textField];
}


-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.scrollerView endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return NO;
}
@end
